package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Food;
import com.itheima.service.FoodService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Chris
 * @Date 2020/9/25 23:58
 */
@RestController
@RequestMapping("/food")
public class FoodController {
    @Reference
    private FoodService foodService;

    @RequestMapping("upload")
    public Result upload(MultipartFile excelFile){

        try {
            //读取Excel文件数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            if (list != null && list.size() > 0) {
                List<Food> foodList = new ArrayList<>();
                for (String[] strings : list) {
                    Food food = new Food(null, strings[0], strings[1], strings[2], strings[3], strings[4]);
                    foodList.add(food);
                }
                foodService.add(foodList);
            }
            return new Result(true, MessageConstant.IMPORT_FILE_SUCCESS);

        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_FILE_FAIL);
        }
    }
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = foodService.pageQuery(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Food food){
        try {
            ArrayList<Food> foodList = new ArrayList<>();
            foodList.add(food);
            foodService.add(foodList);
            return new Result(true,MessageConstant.ADD_FOOD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_FOOD_FAIL);
        }
    }
}
